import json
import sys
import requests

from config import getConfigParams
from requestUrl import getDocByUrl,getEntryIdByQuery
from logs import saveLog
from urllib import parse
from formatContent import formatContent, removeSrcParams

# url = 'https://article.xuexi.cn/articles/index.html?art_id=17330689286560204926&item_id=17330689286560204926&study_style_id=feeds_default&pid=17486757193282890&ptype=75&source=share&share_to=copylink'

# 获取配置参数
configParams = getConfigParams(sys.argv)
url = configParams['real_url']
env = configParams['env']

# 获取文章ID
entryId = getEntryIdByQuery(configParams['real_url'], 'art_id')
articleId = entryId

# 拼接JS链接，从该链接的放回拿到相应数据
jsUrl = 'https://article.xuexi.cn/data/app/' + str(articleId) + '.js?callback=callback'

headers = {
    'referer': 'https://www.xuexi.cn',
}

# 返回的是字符串：callback({这里是json串})
response = requests.get(url=jsUrl, headers=headers)
jsData = json.loads(response.text[9:-1])

# 封面图
coverUrl = ''

# 标题
title = jsData['title']

# 文章正文
articleContent = jsData['content']

# 文章中包含图片的话，需要拼接html
if articleContent.find('<!--{img:0}-->') >= 0:
    html = '<div>'
    count = 0
    for srcInfo in jsData['image']:
        imgStr = '<!--{img:' + str(count) + '}-->'
        newTag = '<p><img src="' + srcInfo['url'] + '" >' + '</p>'
        articleContent = articleContent.replace(imgStr, newTag)
        count = count + 1

# 文章作者
authorName = ''
if 'modifier_name' in jsData['identity']:
    authorName = jsData['identity']['modifier_name']
if 'authorName' in jsData['identity']:
    authorName = jsData['identity']['authorName']

# 是13位的，转成10位
publicTime = str(jsData['identity']['create_timestamp'])[0:10]

# 去【李世泉】那里过滤标签
content = formatContent(articleContent, env=env)

result = {
    'entry_id': entryId,
    'not_format_content': articleContent,
    'content': articleContent,
    'author_name': authorName,
    'cover_url': coverUrl,
    'public_time': publicTime,
    'title': title,
}
logData = {
    'params': sys.argv,
    'result': result
}
saveLog(json.dumps(logData, ensure_ascii=False))
# 结果输出
print(json.dumps(result, ensure_ascii=False))
